package demo1;

public class MyAarrayList implements IArrayList{
    private int[] array;//数组
    private int arrlen;//数组长度
    private int arraysize;//数组有效元素个数
    private static final int ArrayLen = 10;

    public MyAarrayList() {
        this.array = new int[ArrayLen];
        arrlen = ArrayLen;
    }

    public MyAarrayList(int len) {
        this.array = new int[len];
        arrlen = len;
    }

    @Override
    public void add(int data) {
        if(HasLen()) {
            AddArrays();
        }
        array[arraysize] = data;
        this.arraysize++;
    }
    @Override
    public void add(int pos, int data) {
        if(HasLen()) {
            AddArrays();
        }
        if(pos < this.arraysize && pos >= 0) {
            for(int i = arraysize; i > pos;i--) {
                array[i] = array[i - 1];
            }
            array[pos] = data;
            this.arraysize++;
        }else if(pos == this.arraysize) {
            add(data);
        }

    }
    //扩容数组
    private void AddArrays() {
        int[] tmp = new int[this.arrlen * 2];
        for(int i = 0;i < this.arraysize;i++) {
            tmp[i] = array[i];
        }
        this.array = tmp;
        this.arrlen *= 2;
    }
    //检查数组是否装满
    private boolean HasLen() {
        if(arraysize == arrlen) {
            return false;
        }
        return true;
    }


    //打印顺序表
    @Override
    public void display() {
        for(int i = 0;i < this.arraysize;i++) {
            System.out.println(this.array[i]);
        }
    }



    @Override
    public boolean contains(int toFind) {
        return false;
    }

    @Override
    public int indexOf(int toFind) {
        return 0;
    }

    @Override
    public int get(int pos) {
        if(pos < this.arraysize && pos >= 0) {
            return array[pos];
        }else {
            return -1;
        }

    }

    @Override
    public void set(int pos, int value) {
        if(pos < this.arraysize && pos >= 0) {
            array[pos] = value;
        }else {
            System.out.println("更改数组访问异常");
        }
    }

    @Override
    public void remove(int toRemove) {
        for(int i = 0;i < this.arraysize ;i++) {
            if(array[i] == toRemove) {
                for(int j = i;j < this.arraysize - 1;j ++) {
                    array[j] = array[j+1];
                }
                arraysize--;
                System.out.println("删除成功");
                return ;
            }
        }
        System.out.println("没有该数字");
    }

    @Override
    public int size() {
        return this.arraysize;
    }

    @Override
    public void clear() {
        for(int i = arraysize - 1;i >= 0; i--) {
            array[i] = 0;
        }
        this.arraysize = 0;
    }
}
